package com.sc.common.shiro.realm;

import com.sc.common.pojo.Administrator;
import com.sc.common.service.AdministratorService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.SimpleByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class AdministratorRealm extends AuthorizingRealm {
    @Autowired
    AdministratorService as;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection collection) {

        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户名
        String username = (String) token.getPrincipal();

        //通过用户名获取用户
        Administrator admin = as.selectByUsername(username);
        //判断是否存在，不存在则抛出异常UnknownAccountException异常
        if (admin == null)
            throw new UnknownAccountException();
            //判断是否启用，冻结状态抛出异常
        else if (!"1".equals(admin.getStatus()))
            throw new LockedAccountException();

        //存在则存入SimpleAuthenticationInfo中
        //需要传入四个参数：1、登录的对象 2、登录的密码  3、盐值 4、Realm名称
        Object password = admin.getPassword();
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                admin,
                password,
                new SimpleByteSource(admin.getUsername()),
                getName()

        );
        return info;
    }
}
